package com.alex.seo.service.campaign;

import org.springframework.beans.factory.annotation.Required;
import org.springframework.transaction.annotation.Transactional;

import com.alex.seo.dao.campaign.CampaignDao;
import com.alex.seo.dao.group.SiteGroupDao;
import com.alex.seo.dao.site.SiteDao;
import com.alex.seo.domain.campaign.Campaign;
import com.alex.seo.service.GenericServiceException;
import com.alex.seo.service.campaign.dto.CampaignDTO;
import com.alex.seo.service.campaign.executor.CampaignExecutionException;
import com.alex.seo.service.campaign.executor.CampaignExecutor;
import com.alex.seo.service.campaign.executor.CampaignExecutorLookupService;
import com.alex.seo.service.logging.LogType;
import com.alex.seo.service.logging.LoggingService;

@Transactional
public class CampaignServiceBean implements CampaignService {
	
	private LoggingService loggingService;

	private SiteDao siteDao;
	
	private SiteGroupDao siteGroupDao;
	
	private CampaignDao campaignDao;
	
	private CampaignExecutorLookupService campaignExecutorLookupService;
	
	@Required
	public void setLoggingService(LoggingService loggingService) {
		this.loggingService = loggingService;
	}
	
	@Required
	public void setSiteDao(SiteDao siteDao) {
		this.siteDao = siteDao;
	}
	
	@Required
	public void setSiteGroupDao(SiteGroupDao siteGroupDao) {
		this.siteGroupDao = siteGroupDao;
	}
	
	@Required
	public void setCampaignDao(CampaignDao campaignDao) {
		this.campaignDao = campaignDao;
	}
	
	@Required
	public void setCampaignExecutorLookupService(CampaignExecutorLookupService campaignExecutorLookupService) {
		this.campaignExecutorLookupService = campaignExecutorLookupService;
	}
	
	@Override
	public void createCampaign(CampaignDTO campaignDTO) throws GenericServiceException {
		try {
			Campaign campaign = CampaignConverter.convert(campaignDTO, siteDao, siteGroupDao);
			campaignDao.persist(campaign);
			
			loggingService.logEvent(LogType.CAMPAIGN_CREATED, campaign.toString());
			
			CampaignExecutor<Campaign> campaignExecutor = campaignExecutorLookupService.lookup(campaign);
			campaignExecutor.execute(campaign);
		} catch (CampaignExecutionException e) {
			throw new GenericServiceException(e);
		}
	}

}
